import axios from 'axios'
import qs from 'qs'
import common from './common'

const addTimestampToUrl = config => {
    // url添加参数
    let url = config.url, params = config.params, method = config.method,
        api = window.localStorage.getItem('ajaxApi') || '/_api'
    url = api + url // 使用'/_api'识别接口请求
    if (method === 'get' && params && Object.keys(params).length > 0) {
        // get请求统一将params序列化
        url = appendParams(url, qs.stringify(params))
        config.params = {}
    }
    // url请求加上时间戳
    config.url = encodeURI(appendParams(url, '_t=' + new Date().getTime()))

    // if (common.getUrlParam('token_enc')) config.url = encodeURI(appendParams(url, 'token_enc=' + common.getUrlParam('token_enc')))

    function appendParams(url, params) {
        if (url.indexOf('?') >= 0) {
            return url + '&' + params
        } else {
            return url + '?' + params
        }
    }

    return config
}, get = (url, params) => {
    return axios.get(url, {
        params
    })
}, post = (url, data) => {
    return axios.post(url, data)
}

// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    return addTimestampToUrl(config)
}, function (error) {
    return Promise.reject(error)
})

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    return responseSuccess(response)
}, function (error) {
    return responseError(error)
})

function responseSuccess(response) {
    if (response.headers) {
        if (response.headers.redirect) {
            let redirect = response.headers.redirect,
                url = ((response.config.url.indexOf('logout') > -1) ? encodeURI(location.origin) : encodeURI(location.href))
            url = common.delUrlParam(url, 'token_enc')
            window.location.href = encodeURI(common.changeUrlArg(redirect, 'targetUrl', url))
            response.data['redirect'] = redirect
            return response
        } else {
            if (response.config.url.indexOf('allResponse') > -1) {
                return response
            } else {
                if (!response.data.success && response.data.message) {
                    common.messageBox('alert', response.data.message, action => {
                        if (window.globalMessageBox) window.globalMessageBox(action)
                    })
                }
                return response.data
            }
        }
    } else {
        if (!response.success && response.message) {
            common.messageBox('alert', response.message)
        }
        return response
    }
}

// 错误拦截
function responseError(error) {
    if (error.response) {
        if (error.response.data.message) {
            common.messageBox('alert', error.response.data.message)
        }
    } else {
        if (error.message) {
            common.messageBox('alert', error.message)
        }
    }
    // common.updateView()
    return Promise.reject(error)
}

export default {
    get,
    post,
    responseSuccess,
    responseError
}
